﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace OpenSearchExplorer
{
    /// <summary>
    /// Interaction logic for OSDDSelectPage.xaml
    /// </summary>
    public partial class OSDDSelectPage : Page
    {
        public OSDDSelectPage()
        {
            InitializeComponent();
            LoadPersistedUrls();
        }

        ~OSDDSelectPage()
        {
            Properties.Settings.Default.Save();
        }

        private void LoadPersistedUrls()
        {
            System.Collections.Specialized.StringCollection osddUrls = Properties.Settings.Default.OsddUrls;
            foreach (string osddUrl in osddUrls)
            {
                urlTextBox.Items.Add(osddUrl);
            }
        }

        private void urlTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            goButton.IsEnabled = urlTextBoxContentIsValid();
        }

        private bool urlTextBoxContentIsValid()
        {
            bool containsWellFormedUri = System.Uri.IsWellFormedUriString(urlTextBox.Text, UriKind.Absolute);
            return containsWellFormedUri;
        }

        private void goButton_Click(object sender, RoutedEventArgs e)
        {
            GoToDisplayPage();
        }

        private void GoToDisplayPage()
        {
            OSDDDisplayPage osddDisplayPage = new OSDDDisplayPage();
            if (osddDisplayPage.getOsdd(new Uri(urlTextBox.Text)))
            {
                this.NavigationService.Navigate(osddDisplayPage);
                persistUrl(urlTextBox.Text);
            }
        }

        private void persistUrl(string url)
        {
            if (! Properties.Settings.Default.OsddUrls.Contains(url))
            {
                Properties.Settings.Default.OsddUrls.Add(url);
            }
        }

        private void urlTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.Return) && urlTextBoxContentIsValid())
            {
                GoToDisplayPage();
            }
        }

    }
}
